#-*- coding: utf-8 -*-
#! /usr/bin/python

import time
from PAM30 import PAMIE
import win32api
import win32con
import ConfigParser
import hashlib


def setRegValue(keystr, vname, value):
    '''
    设置某个注册表项的值，不存在则先添加项再设置值
    '''
    key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keystr, 0, win32con.KEY_ALL_ACCESS)
    try:
        kv = win32api.RegQueryValueEx(key, vname)
        if(kv==value):
            return True
        else:
            win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, value)
            win32api.RegCloseKey(key)
    except:
        win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, value)
        win32api.RegCloseKey(key)
        return True


def initConfig(filename):
    '''
    去掉文件头BOM等
    Window下用记事本打开配置文件并修改保存后，编码为UNICODE
    或UTF-8的文件的文件头
    #会被相应的加上\xff\xfe（\xff\xfe）或\xef\xbb\xbf
    '''
    import re
    content = open(filename).read()
    content = re.sub(r"\xfe\xff", "", content)
    content = re.sub(r"\xff\xfe", "", content)
    content = re.sub(r"\xef\xbb\xbf", "", content)
    open(filename, 'w').write(content)


def isMeal(url):
    '''
    判断网址是不是套餐
    '''
    if(url.find('http://meal.taobao.com')):
        return True
    else:
        return False


def lgTaobao(username, userpass):
    '''
    使用指定用户名密码（在IE）登录淘宝
    ''' 
    lgurl = 'https://login.taobao.com/member/login.jhtml'
    ie.navigate(lgurl)
    time.sleep(0.5)
    win32api.keybd_event(122, 0, 0, 0)#f11
    win32api.keybd_event(122, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(0.5)    
    ie.setTextBox('TPL_username', username.decode('utf-8'))
    time.sleep(0.3) 
    ie.setCheckBox('J_SafeLoginCheck', 0)
    time.sleep(0.2)
    bt = ie.findElement('button', 'id', 'J_SubmitStatic')
    time.sleep(0.3) 
    ie.clickElement(bt)
    #ie.setTextBox('TPL_password', userpass)
    typeme(userpass)
    time.sleep(1.5)
    ie.clickElement(bt)
    time.sleep(1.5)
    if(ie.findText(username.decode('utf-8'))):
        return True
    else:
        return False


def ordd(str):
    '''
    解决键盘码不对应问题,不知道别的电脑有没有这个问题
    '''
    t = ord(str)
    #65到90是A到Z
    if(t>90):
        return t-32
    else:
        return t


def typeme(passw):
    '''
    模拟人工输入,自动输入参数字符串到焦点窗口
    '''
    psht = len(passw)
    for j in range(psht):
        win32api.keybd_event(ordd(passw[j]), 0, 0, 0)
        time.sleep(0.5)
        win32api.keybd_event(ordd(passw[j]), 0, win32con.KEYEVENTF_KEYUP, 0)
        time.sleep(0.5)


def pai(ppass):
        try:
            #拍下
            time.sleep(1.5)
            buy = ie.findElement('div', 'id', 'J_juValid')
            a = ie.getElementChildren(buy)
            b = ie.getElementChildren(a[0])
            eleArry = ie.getElementChildren(buy)
            ie.clickElement(b[0])
            time.sleep(2)
            #购买
            go = ie.findElement('a', 'id', 'J_Go')
            ie.clickElement(go)
            time.sleep(3)
            #到支付页面
            pp = ie.findElement('input', 'id', 'payPassword')
            ie.clickHiddenElement(pp)
            pay = ie.findElement('input', 'id', 'J_authSubmit')
            ie.clickElement(pay)
            time.sleep(1)
            #支付
            typeme(ppass)
            ie.clickElement(pay)
            time.sleep(2)
            #退出
            ie.clickHiddenLink('J_Logout')
            time.sleep(1.5)
        except:
            exit(0)
def makesn(ww):
    '''
    ww 是旺旺主号
    '''
    x = hashlib.sha224((hashlib.md5(ww)).hexdigest()+'jhfaixiaobao')
    return x.hexdigest()

        
#读取配置文件
keystr = 'SOFTWARE\\Microsoft\\Internet Explorer\\New Windows\\Allow'
setRegValue(keystr, 's.taobao.com', '0')
config = ConfigParser.ConfigParser()
initConfig('pai4.ini')
config.read('pai4.ini')
mtaoid = config.get("global", "mtaoid")
sn = config.get("global", "sn")
if(not makesn(mtaoid)==sn):
    print 'SN Error!!'
    exit(0)
xiaohaocount = int(config.get("global", "xiaohaocount"))
item = config.get("global", "item")
xiaohao = range(xiaohaocount)
lpass = range(xiaohaocount)
ppass = range(xiaohaocount)
ie= PAMIE()
for i in range(xiaohaocount):
    time.sleep(1.2)    
    xiaohao[i] = config.get("xiaohao", "hao"+str(i+1))    
    lpass[i] = config.get("lpass", "lpass"+str(i+1))    
    ppass[i] = config.get("ppass", "ppass"+str(i+1))    
    time.sleep(1.5)
    if(lgTaobao(xiaohao[i], lpass[i])):
        try:
            ie.navigate(item)
            pai(ppass[i])    
        except:
            print 'Pai Error!!'
            break
        time.sleep(1.5)
    print 'Login Error!!'

